package com.example.essearchdemo.product;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Component
@Profile("!prod")
public class DemoDataLoader {
    private static final Logger log = LoggerFactory.getLogger(DemoDataLoader.class);
    private final ProductIndexService indexService;

    public DemoDataLoader(ProductIndexService indexService) {
        this.indexService = indexService;
    }

    @PostConstruct
    public void load() {
        try {
            // 等待一秒让索引初始化完成
            Thread.sleep(1000);

            List<Product> list = new ArrayList<>();

            list.add(build("Apple iPhone 15 Pro", "phone", 9999.0, 4.8, "black", "6.1", "Apple", "titanium"));
            list.add(build("Apple iPhone 15", "phone", 6999.0, 4.6, "blue", "6.1", "Apple", "aluminum"));
            list.add(build("Xiaomi 14 Pro", "phone", 4999.0, 4.5, "white", "6.7", "Xiaomi", "metal"));
            list.add(build("Huawei Mate 60 Pro", "phone", 5999.0, 4.7, "green", "6.8", "Huawei", "glass"));
            list.add(build("Nike Air Zoom Pegasus", "shoes", 899.0, 4.4, "gray", "42", "Nike", "mesh"));
            list.add(build("Adidas Ultraboost", "shoes", 1199.0, 4.6, "black", "43", "Adidas", "primeknit"));
            list.add(build("Lenovo ThinkPad X1", "laptop", 10999.0, 4.7, "black", "14", "Lenovo", "carbon"));
            list.add(build("MacBook Air M2", "laptop", 8999.0, 4.8, "silver", "13.6", "Apple", "aluminum"));
            list.add(build("Samsung Galaxy S24", "phone", 7999.0, 4.5, "purple", "6.2", "Samsung", "glass"));
            list.add(build("Dell XPS 13", "laptop", 9999.0, 4.6, "white", "13.4", "Dell", "aluminum"));

            indexService.bulkIndex(list);
            log.info("Demo data loaded successfully: {} products", list.size());
        } catch (Exception e) {
            log.warn("Failed to load demo data: {}", e.getMessage());
        }
    }

    private Product build(String name, String category, double price, double rating,
                          String color, String size, String brand, String material) {
        Product p = new Product();
        p.setId(UUID.randomUUID().toString());
        p.setName(name);
        p.setCategory(category);
        p.setPrice(price);
        p.setRating(rating);
        p.setColor(color);
        p.setSize(size);
        Map<String, Object> attrs = new HashMap<>();
        attrs.put("brand", brand);
        attrs.put("material", material);
        p.setAttributes(attrs);
        return p;
    }
}